using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;

namespace RSSRadio
{
	/// <summary>
	/// Settings for the desktop application which get stored to XML.
	/// </summary>
	public class AppSettings
	{
		public string DownloadedPodcastDir;
		public bool AutomaticUpdatesEnabled;
        public int podcastExpirationDays;

        [System.Xml.Serialization.XmlIgnoreAttribute]
		public string DownloadedPodcastListXmlLoc;

        private string SettingsFolder;
        private string SettingsXmlLoc;

        private static string[] sCards = null;

        static AppSettings()
        {
            sCards = GetStorageCardNames();
        }

		public AppSettings()
		{
			try
			{
                SettingsFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RSSRadio";
			}
			catch
			{
				// workaround lack of application data folder on WM 2003
                SettingsFolder = "\\Program Files\\RSSRadio";
			}

            SettingsXmlLoc = SettingsFolder + "\\PPSettings.xml";

			// application default values
			if (hasStorageCard())
				DownloadedPodcastDir = getStorageCardPodcastFolder();
			else
				DownloadedPodcastDir = getDevicePodcastFolder();

            DownloadedPodcastListXmlLoc = SettingsFolder + "\\PodcastList.xml";

			AutomaticUpdatesEnabled = true;

            podcastExpirationDays = 14;

			// create a new settings file if none found
			if (!File.Exists(SettingsXmlLoc))
			{
                if (!Directory.Exists(SettingsFolder))
                {
                    Directory.CreateDirectory(SettingsFolder);
                }

				TextWriter tw = new StreamWriter(SettingsXmlLoc);
				XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));
				serializer.Serialize(tw, this);
				tw.Close();
			}
		}

        public static bool hasStorageCard()
        {
            return (sCards != null && sCards.Length > 0);
        }
        public static string getStorageCardPodcastFolder()
        {
            //Return the last storage card as some postings on net indicate the first one is often the main storage
            if (sCards == null || sCards.Length == 0) throw new InvalidOperationException("No Storage card");
           
            return sCards[sCards.Length -1] + @"\Podcasts";
        }
        public static string getDevicePodcastFolder()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Podcasts";
        }

        public static string[] GetStorageCardNames()
        {
            FileAttributes attrStorageCard = FileAttributes.Directory | FileAttributes.Temporary;
            List<string> scards = new List<string>();

            DirectoryInfo rootDir = new DirectoryInfo(@"\");

            foreach (DirectoryInfo di in rootDir.GetDirectories())
            {
                //if directory and temporary
                if ((di.Attributes & attrStorageCard) == attrStorageCard)
                {
                    //add to collection of storage cards
                    scards.Add(di.FullName);
                }
            }
            return scards.ToArray();
        }

		/// <summary>
		/// Reads the settings file.
		/// </summary>
		public void Read()
		{
			XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));
			if (File.Exists(SettingsXmlLoc))
			{
				// read in existing settings
				TextReader tr = new StreamReader(SettingsXmlLoc);
				AppSettings ppTmp = (AppSettings)serializer.Deserialize(tr);
				this.AutomaticUpdatesEnabled = ppTmp.AutomaticUpdatesEnabled;
				this.DownloadedPodcastDir = ppTmp.DownloadedPodcastDir;

				tr.Close();
			}
			else
				throw new FileNotFoundException("Settings file not found");

			// Create the downloaded podcasts directory if it does not exist.
			if (!Directory.Exists(this.DownloadedPodcastDir))
			{
				Directory.CreateDirectory(this.DownloadedPodcastDir);
			}
		}

		public void Save()
		{
			if (File.Exists(SettingsXmlLoc))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));
				TextWriter tw = new StreamWriter(SettingsXmlLoc);
				serializer.Serialize(tw, this);
				tw.Close();
			}
			else
				throw new FileNotFoundException("Settings file not found");
		}

        public String getSettingsFolder()
        {
            return this.SettingsFolder;
        }
	}
}